﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System.IO;
using System.Threading;

namespace Exdot
{
    public partial class Form1 : DevComponents.DotNetBar.Metro.MetroForm
    {
        IOLog log = new IOLog();
        Prompt_Manager pm = new Prompt_Manager();
        Income_Manager im = new Income_Manager();
        IOMoney reMoney = new IOMoney();
        Plan kh = new Plan();
        Statictis sta = new Statictis();
        IOMinMoney minMoneyIO = new IOMinMoney();
        int switchButton = 1;
        public Form1()
        {
            Thread t = new Thread(new ThreadStart(SplashScreen));
            t.Start();
            Thread.Sleep(5000);
            InitializeComponent();
            t.Abort();
            this.tabMain.Appearance = TabAppearance.FlatButtons;
            tabMain.ItemSize = new Size(0, 1);
            tabMain.SizeMode = TabSizeMode.Fixed;
            this.advTree1.Visible = false;
            Point a = new Point(150, 12);
            this.tabMain.Location = a;
            Point b = new Point(208, 287);
            this.bubbleBar1.Location = b;
            Prompt_ThongBao();
            Plan_Thongbao();
            reMoney_load();
            minMoneyIO_load();
            mainMenuEnable();
        }
        public void reMoney_load()
        {
            try
            {
                this.mtMoneyRe.Text = "<font face=\"Comic Sans MS\" size=\"17\" /><i> TKHT:" + reMoney.ReadFile() + " VNĐ</i>";
            }
            catch
            {
                String money=Prompt.ShowDialog("*Nhập số tiền:", "FIRST-MONEY");
                reMoney.WriteFile(money);
                reMoney_load();
            }
        }
        
        #region notUse
        private void colorPickerDropDown1_SelectedColorChanged(object sender, EventArgs e)
        {

        }

        private void slide_In()
        {
            timer2.Start();
        }
        private void slide_Out()
        {
            timer1.Start();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            slide_Out();
            slide_In();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            itemPanel1.Width=itemPanel1.Width-10;
            if(itemPanel1.Width<1)
            timer1.Stop();
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            itemPanel1.Width = itemPanel1.Width + 20;
            if (itemPanel1.Width > 558)
                timer2.Stop();
        }
        #endregion
        private void buttonX1_MouseHover(object sender, EventArgs e)
        {
            this.advTree1.Visible = true;
            Point a = new Point(227, 12);
            this.tabMain.Location = a;

            Point b = new Point(309, 287);
            this.bubbleBar1.Location = b;

        }

        private void buttonX1_MouseLeave(object sender, EventArgs e)
        {
            this.advTree1.Visible = false;
            Point a = new Point(150, 12);
            this.tabMain.Location = a;

            Point b = new Point(208, 287);
            this.bubbleBar1.Location = b;
        }
        #region tab

        private void mtCustomize_DoubleClick(object sender, EventArgs e)
        {
            this.tabMain.SelectedIndex = 7;
            nhacNhoShow();
            this.nhacnhoEnable();
        }

        private void mtExpense_DoubleClick(object sender, EventArgs e)
        {
            this.tabMain.SelectedIndex = 1;
            QuanLyChiTieuEntities context = new QuanLyChiTieuEntities();
            var query1 = from ChiTieu in context.ChiTieux select ChiTieu;
            var query = new[] { new ChiTieu() }.Concat(query1);
            dgvQLChiTieu.DataSource = query.ToList();
            this.setDTGridViewCT();
            tn_ctEnable();
        }

        private void mtStatistic_DoubleClick(object sender, EventArgs e)
        {
            this.tabMain.SelectedIndex = 2;
            thongKeShow();
            this.thongke_chartEnable();
        }

        private void mtIncome_DoubleClick(object sender, EventArgs e)
        {
            this.tabMain.SelectedIndex = 3;
            thuNhapShow();
            tn_ctEnable();
        }

        private void mtPrompt_DoubleClick(object sender, EventArgs e)
        {
            this.tabMain.SelectedIndex = 4;
            mainMenuEnable();
        }

        private void mtSystem_DoubleClick(object sender, EventArgs e)
        {
            this.tabMain.SelectedIndex = 5;
            this.mainMenuEnable();
        }

        private void node1_NodeClick(object sender, EventArgs e)
        {
            this.tabMain.SelectedIndex = 0;
        }

        private void mtBackup_DoubleClick(object sender, EventArgs e)
        {
            this.tabMain.SelectedIndex = 8;
            backup_Load();
            this.mainMenuEnable();
        }

        private void mtRestore_DoubleClick(object sender, EventArgs e)
        {
            this.tabMain.SelectedIndex = 9;
            restore_Load();
        }

        private void mtDefault_DoubleClick(object sender, EventArgs e)
        {
            this.tabMain.SelectedIndex = 6;
            this.mainMenuEnable();
            this.mainMenuEnable();
        }
        #endregion

        #region Show
        public void nhacNhoShow()
        {
            dataGridViewNNTuyChon.DataSource = pm.nhacNhoShow();
            this.setDTGridViewNN();
        }
        public void thuNhapShow()
        {
            dataGridViewTN.DataSource = im.thuNhapShow();
            this.tabMain.SelectedIndex = 3;
        }
        public void keHoachShow()
        {
            dataGridViewKH.DataSource = kh.keHoachShow();
            setDTGridViewKH();
        }
        public void thongKeShow()
        {
            dataGridViewTK.DataSource = sta.thongKeShow();
        }
        #region Backup
        String Database = "QuanLyChiTieu";
        String ConnectionString = "server=DINHHUY-PC; Database=QuanLyChiTieu; Integrated Security=SSPI";
        String Server = "DINHHUY-PC";
        void backup_Load()
        {
            this.Text = "Sao lưu dữ liệu Database: " + Database;
            DateTime now = DateTime.Now;
            txtThuMuc.Text = @"D:\";
            txtName.Text = "QLCH_" + now.Day + "-" + now.Month + "-" + now.Year + "_" + now.Hour + "-" + now.Minute + "-" + now.Second;
        }
        void BackUp()
        {
            txtThuMuc.Enabled = txtName.Enabled = btnThuMuc.Enabled = btnOK.Enabled = btnCancel.Enabled = false;
            string sConnect = ConnectionString;
            string backUpPath = txtThuMuc.Text + @"\" + txtName.Text + ".bak";
            string dbName = Database;
            using (SqlConnection cnn = new SqlConnection(sConnect))
            {
                cnn.Open();
                dbName = cnn.Database.ToString();

                ServerConnection sc = new ServerConnection(cnn);
                Server sv = new Server(sc);

                // Create backup device item for the backup
                BackupDeviceItem bdi = new BackupDeviceItem(backUpPath, DeviceType.File);

                // Create the backup informaton
                Backup bk = new Backup();
                bk.PercentComplete += new PercentCompleteEventHandler(bkp_PercentComplete);
                bk.Devices.Add(bdi);
                bk.Action = BackupActionType.Database;
                bk.PercentCompleteNotification = 1;
                bk.BackupSetDescription = dbName;
                bk.BackupSetName = dbName;
                bk.Database = dbName;
                //bk.ExpirationDate = DateTime.Now.AddDays(30);
                bk.LogTruncation = BackupTruncateLogType.Truncate;
                bk.FormatMedia = false;
                bk.Initialize = true;
                bk.Checksum = true;
                bk.ContinueAfterError = true;
                bk.Incremental = false;
                // Run the backup
                bk.SqlBackup(sv);//Exception
                cnn.Close();
            }
        }
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (txtThuMuc.Text != "" && txtName.Text != "")
            {
                string backUpPath = txtThuMuc.Text + @"\" + txtName.Text + ".bak";
                if (File.Exists(backUpPath))
                {
                    MessageBox.Show("Tên File Đã tồn tại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    try
                    {
                        BackUp();
                    }
                    catch (Exception ex)
                    {
                        log.WriteFile(ex.Message);
                    }
                }
            }
        }
        void bkp_PercentComplete(object sender, PercentCompleteEventArgs e)
        {
            this.pbTienDo.Value = e.Percent;
            this.pbTienDo.Text = e.Percent + "%";
            if (e.Percent == 100)
            {
                MessageBox.Show("BackUp Thành Công", "Thông báo");
                btnCancel.Enabled = true;
            }
        }

        private void btnThuMuc_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                txtThuMuc.Text = folderBrowserDialog.SelectedPath;
        }
        #endregion

        #region Restore
        void restore_Load()
        {
            txtThuMucR.Text = @"D:\";
        }
        private void btnThuMucR_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialogR.ShowDialog() == DialogResult.OK)
            {
                txtThuMucR.Text = folderBrowserDialogR.SelectedPath;
            }
        }
        private void cbFileName_SelectedIndexChanged(object sender, EventArgs e)
        {
            FileInfo file = new FileInfo(txtThuMucR.Text + "\\" + cbFileName.Text);
            dtpNgayTao.Value = file.LastAccessTime;
            txtDungLuong.Text = file.Length / 1024 + " Kb";
        }


        private void btnOKR_Click(object sender, EventArgs e)
        {
            string sConnect = ConnectionString;
            if (txtThuMucR.Text != "")
            {
                try
                {
                    txtThuMucR.Enabled = cbFileName.Enabled = btnThuMucR.Enabled = btnOKR.Enabled = btnCancelR.Enabled = false;
                    //ngắt kết nối cơ sở dữ liệu
                    using (SqlConnection cnn = new SqlConnection(sConnect))
                    {
                        SqlCommand command = cnn.CreateCommand();
                        command.CommandText = "alter Database " + Database + " Set OFFLINE with ROLLBACK IMMEDIATE alter Database " + Database + " Set ONLINE";
                        cnn.Open();
                        command.ExecuteNonQuery();
                        cnn.Close();
                    }
                    ServerConnection connection = new ServerConnection(Server);

                    Server databaseServer = new Server(connection);

                    //Create an instance of the restore object.   
                    Restore res = new Restore();

                    //The name of the database that will be restored.
                    res.Database = Database;

                    //Restore options      
                    res.Action = RestoreActionType.Database;
                    //Name of backup file
                    res.Devices.AddDevice(txtThuMucR.Text + @"\" + cbFileName.Text, DeviceType.File);
                    res.ReplaceDatabase = true;
                    res.PercentComplete += new PercentCompleteEventHandler(bkp_PercentCompleteR);
                    //Execute the restore   
                    res.SqlRestore(databaseServer);
                    databaseServer.Refresh();

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Phục hồi dữ liệu thất bại", "Thông báo");
                    btnCancel.Enabled = true;
                    log.WriteFile(ex.Message);
                }
            }
        }
        void bkp_PercentCompleteR(object sender, PercentCompleteEventArgs e)
        {
            this.pbTienDoR.Value = e.Percent;
            this.pbTienDoR.Text = e.Percent + "%";
            if (e.Percent == 100)
            {
                MessageBox.Show("Phục hồi dữ liệu thành công", "Thông báo");
                btnCancelR.Enabled = true;
            }
        }
        private void txtThuMucR_TextChanged(object sender, EventArgs e)
        {
            if (txtThuMucR.Text != "")
            {
                cbFileName.Items.Clear();

                DirectoryInfo curFolder = new DirectoryInfo(txtThuMucR.Text);
                foreach (FileInfo file in curFolder.GetFiles())
                {
                    string[] t = file.FullName.Split('.');
                    if (t[t.Length - 1] == "bak")
                        cbFileName.Items.Add(file.Name);
                }
                if (cbFileName.Items.Count > 0)
                    cbFileName.SelectedIndex = 0;
            }
        }
        #endregion

        #region Nhac Nho Mac Dinh

        public void minMoneyIO_load()
        {
            try
            {
                String s = minMoneyIO.ReadFile();
                if (s != "")
                {
                    cbNNTienToiThieu.Checked = true;
                    txtMinMoney.Text = s;
                    String money = reMoney.ReadFile();
                    if (int.Parse(money) < int.Parse(txtMinMoney.Text))
                        MessageBox.Show("tài khoản của bạn đang dưới mức tối thiểu");
                }
                
            }
            catch { }
        }

        private void cbNNTienToiThieu_CheckedChanged(object sender, EventArgs e)
        {
            if (cbNNTienToiThieu.Checked)
            {
                this.txtMinMoney.Enabled=true;
                this.btnXacNhan.Enabled = true;
            }
            else
            {
                this.txtMinMoney.Enabled = false;
                this.btnXacNhan.Enabled = false;
                try
                {
                    minMoneyIO.deleteFile();
                }
                catch
                {
                    MessageBox.Show("can't delete");
                }
            }
        }

        private void mtMoneyRe_TextChanged(object sender, EventArgs e)
        {
            if (txtMinMoney.Enabled)
            {
                String money=reMoney.ReadFile();
                if (int.Parse(money) < int.Parse(txtMinMoney.Text))
                    MessageBox.Show("tài khoản của bạn đang dưới mức tối thiểu");
            }
        }


        private void btnXacNhan_Click(object sender, EventArgs e)
        {
            minMoneyIO.WriteFile(this.txtMinMoney.Text);
            mtMoneyRe_TextChanged(sender, e);
        }


        private void switchButton1_ValueChanged(object sender, EventArgs e)
        {
            if (switchButton1.Value == true)
            {
                switchButton = 0;
            }
            else
            {
                switchButton = 1;
            }
        }
        #endregion

        #endregion
        #region Add
        private void bubbleButton1_Click(object sender, DevComponents.DotNetBar.ClickEventArgs e)
        {
            switch (this.tabMain.SelectedIndex)
            {
                case 1:
                    ThemChiTieu(sender, e);
                    break;
                case 7:
                    NhacNhoTuyChon a = takeNNRow();
                    MessageBox.Show(pm.nhacNhoInsert(a));
                    this.dataGridViewNNTuyChon.DataSource = null;
                    nhacNhoShow();
                    break;
                case 3:
                    //ThuNhap tn = takeTNRow();
                    //MessageBox.Show(im.thuNhapInsert(tn));
                    //this.dataGridViewTN.DataSource = null;
                    //thuNhapShow();
                    try
                    {
                        QuanLyChiTieuEntities context = new QuanLyChiTieuEntities();
                        ThuNhap tn = new ThuNhap();
                        tn.TenTN = (string)(dataGridViewTN.SelectedCells[1].Value);
                        tn.SoTien = (double)(dataGridViewTN.SelectedCells[2].Value);
                        tn.ThoiGian = (DateTime)(dataGridViewTN.SelectedCells[3].Value);
                        tn.MoTa = (string)(dataGridViewTN.SelectedCells[4].Value);
                            Double money = Double.Parse(this.reMoney.ReadFile());
                            money = money + tn.SoTien;
                            reMoney.WriteFile(money.ToString());
                            reMoney_load();
                        context.ThuNhaps.AddObject(tn);
                        context.SaveChanges();
                        mtExpense_DoubleClick(sender, e);
                        thuNhapShow();
                        MessageBox.Show("Thêm thành công");
                    }
                    catch(Exception r)
                    {
                        MessageBox.Show("Thêm thu nhập thất bại "+r.Message);
                        log.WriteFile("Thêm thu nhập thất bại " + r.Message);
                    }
                    break;
                case 10:
                    KeHoachChiTieu k = takeKHRow();
                    MessageBox.Show(kh.keHoachInsert(k));
                    this.dataGridViewKH.DataSource = null;
                    keHoachShow();
                    break;
            }
        }
        public void ThemChiTieu(object sender, EventArgs e)
        {
            try
            {
                QuanLyChiTieuEntities context = new QuanLyChiTieuEntities();
                ChiTieu ct = new ChiTieu();
                    ct.TenChiTieu = (string)(dgvQLChiTieu.SelectedCells[1].Value);
                    ct.SoTien = (double)(dgvQLChiTieu.SelectedCells[2].Value);
                    ct.ThoiGian = (DateTime)(dgvQLChiTieu.SelectedCells[3].Value);
                    ct.MoTa = (string)(dgvQLChiTieu.SelectedCells[4].Value);
                    ct.TrangThai = dgvQLChiTieu.SelectedCells[5].Value.ToString();
                if (ct.TrangThai.Substring(0, 1) == "D")
                {
                    Double money = Double.Parse(this.reMoney.ReadFile());
                    money = money - ct.SoTien;
                    reMoney.WriteFile(money.ToString());
                    reMoney_load();
                }
                context.ChiTieux.AddObject(ct);
                context.SaveChanges();
                mtExpense_DoubleClick(sender, e);
                MessageBox.Show("Thêm thành công, Mã Chi Tiêu mới thêm Là: " + ct.MaChiTieu.ToString());
            }
            catch
            {
                log.WriteFile("Thêm Chi Tiêu Thất Bại");
                MessageBox.Show("Thêm Chi Tiêu thất bại");                
            }
        }
        public void ThemChiTieu(String tenCT,double tien,DateTime tg,String mt)
        {
            try
            {
                QuanLyChiTieuEntities context = new QuanLyChiTieuEntities();
                ChiTieu ct = new ChiTieu();
                ct.TenChiTieu = tenCT;
                ct.SoTien = tien;
                ct.ThoiGian = tg;
                ct.MoTa = mt;
                ct.TrangThai = "DaTra";
                if (ct.TrangThai.Substring(0, 1) == "D")
                {
                    Double money = Double.Parse(this.reMoney.ReadFile());
                    money = money - ct.SoTien;
                    reMoney.WriteFile(money.ToString());
                    reMoney_load();
                }
                context.ChiTieux.AddObject(ct);
                context.SaveChanges();
                MessageBox.Show("Thêm thành công, Mã Chi Tiêu mới thêm Là: " + ct.MaChiTieu.ToString());
            }
            catch
            {
                log.WriteFile("Thêm Chi Tiêu Thất Bại");
                MessageBox.Show("Thêm Chi Tiêu thất bại");        
            }
        }

        #endregion

        #region Takerow
        private NhacNhoTuyChon takeNNRow()
        {
            NhacNhoTuyChon kq = new NhacNhoTuyChon();
            try
            {
                if (int.Parse(dataGridViewNNTuyChon.SelectedRows[0].Cells[0].Value.ToString()) != 0)
                    kq.STT = int.Parse(dataGridViewNNTuyChon.SelectedRows[0].Cells[0].Value.ToString());
                kq.TenNhacNho = dataGridViewNNTuyChon.SelectedRows[0].Cells["TenNhacNho"].Value.ToString();
                kq.NoiDung = dataGridViewNNTuyChon.SelectedRows[0].Cells["NoiDung"].Value.ToString();
                kq.ThoiGian = Convert.ToDateTime(dataGridViewNNTuyChon.SelectedRows[0].Cells["ThoiGian"].Value.ToString());
                // MessageBox.Show(dataGridViewNNTuyChon.SelectedRows[0].Cells["ThoiGian"].Value.ToString());
                kq.TrangThai = dataGridViewNNTuyChon.SelectedRows[0].Cells["TrangThai"].Value.ToString();
            }
            catch
            {
            }
            return kq;
        }
        private ThuNhap takeTNRow()
        {
            ThuNhap kq = new ThuNhap();
            try
            {
                if (int.Parse(dataGridViewTN.SelectedRows[0].Cells[0].Value.ToString()) != 0)
                    kq.MaThuNhap = int.Parse(dataGridViewTN.SelectedRows[0].Cells[0].Value.ToString());
                kq.TenTN = dataGridViewTN.SelectedRows[0].Cells["TenTN"].Value.ToString();
                kq.SoTien = float.Parse(dataGridViewTN.SelectedRows[0].Cells["SoTien"].Value.ToString());
                kq.ThoiGian = Convert.ToDateTime(dataGridViewTN.SelectedRows[0].Cells["ThoiGian"].Value.ToString());
                //  MessageBox.Show(dataGridViewNNTuyChon.SelectedRows[0].Cells["ThoiGian"].Value.ToString());
                kq.MoTa = dataGridViewTN.SelectedRows[0].Cells["MoTa"].Value.ToString();
            }
            catch
            {

            }
            return kq;
        }
        private KeHoachChiTieu takeKHRow()
        {
            KeHoachChiTieu kq = new KeHoachChiTieu();
            try
            {
                double money = double.Parse(reMoney.ReadFile());
                if (int.Parse(dataGridViewKH.SelectedRows[0].Cells[0].Value.ToString()) != 0)
                    kq.MaKeHoach = int.Parse(dataGridViewKH.SelectedRows[0].Cells[0].Value.ToString());
                kq.TenKeHoach = dataGridViewKH.SelectedRows[0].Cells["TenKeHoach"].Value.ToString();
                kq.MoTa = dataGridViewKH.SelectedRows[0].Cells["MoTa"].Value == null ? "" : dataGridViewKH.SelectedRows[0].Cells["MoTa"].Value.ToString();
                kq.ThoiGian = Convert.ToDateTime(dataGridViewKH.SelectedRows[0].Cells["ThoiGian"].Value.ToString());
                kq.SoTien = Double.Parse(dataGridViewKH.SelectedRows[0].Cells["SoTien"].Value.ToString());
                kq.TrangThai = dataGridViewKH.SelectedRows[0].Cells["TrangThai"].Value.ToString();
            }
            catch
            {
            }
            return kq;
        }
        #endregion

        #region SetDatagridview
        private void setDTGridViewNN()
        {
            int n = 0;
            n = this.dataGridViewNNTuyChon.RowCount;
            DataGridViewComboBoxCell cbc = new DataGridViewComboBoxCell();
            cbc.Items.Add("Active");
            cbc.Items.Add("Finish");
            cbc.Items.Add("Delay");
            this.dataGridViewNNTuyChon[4, 0] = cbc;
            this.dataGridViewNNTuyChon[4, 0].Value = cbc.Items[0];
            for (int i = 1; i < n; i++)
            {
                cbc = new DataGridViewComboBoxCell();
                cbc.Items.Add("Active");
                cbc.Items.Add("Finish");
                cbc.Items.Add("Delay");
                this.dataGridViewNNTuyChon[4, i] = cbc;
                if (this.dataGridViewNNTuyChon[4, i].Value.ToString().Substring(0, 1) == "A")
                {
                    this.dataGridViewNNTuyChon[4, i].Value = cbc.Items[0];
                }
                if (this.dataGridViewNNTuyChon[4, i].Value.ToString().Substring(0, 1) == "F")
                {
                    this.dataGridViewNNTuyChon[4, i].Value = cbc.Items[1];
                }
                if (this.dataGridViewNNTuyChon[4, i].Value.ToString().Substring(0, 1) == "D")
                {
                    this.dataGridViewNNTuyChon[4, i].Value = cbc.Items[2];
                }
            }
        }

        private void setDTGridViewKH()
        {
            int n = 0;
            n = this.dataGridViewKH.RowCount;
            DataGridViewComboBoxCell cbc = new DataGridViewComboBoxCell();
            cbc.Items.Add("Active");
            cbc.Items.Add("Finish");
            cbc.Items.Add("Delay");
            this.dataGridViewKH[6, 0] = cbc;
            this.dataGridViewKH[6, 0].Value = cbc.Items[0];
            double money=double.Parse(reMoney.ReadFile());
            for (int i = 1; i < n; i++)
            {
                cbc = new DataGridViewComboBoxCell();
                cbc.Items.Add("Active");
                cbc.Items.Add("Finish");
                cbc.Items.Add("Delay");
                this.dataGridViewKH[6, i] = cbc;
                if (this.dataGridViewKH[6, i].Value.ToString().Substring(0, 1) == "A")
                {
                    this.dataGridViewKH[6, i].Value = cbc.Items[0];
                    this.dataGridViewKH[3, i].Value = money - double.Parse(this.dataGridViewKH[5, i].Value.ToString());
                }
                if (this.dataGridViewKH[6, i].Value.ToString().Substring(0, 1) == "F")
                {
                    this.dataGridViewKH[6, i].Value = cbc.Items[1];
                }
                if (this.dataGridViewKH[6, i].Value.ToString().Substring(0, 1) == "D")
                {
                    this.dataGridViewKH[6, i].Value = cbc.Items[2];
                    this.dataGridViewKH[3, i].Value = money - double.Parse(this.dataGridViewKH[5, i].Value.ToString());
                }
            }
        }

        private void setDTGridViewCT()
        {
            int n = 0;
            n = this.dgvQLChiTieu.RowCount;
            DataGridViewComboBoxCell cbc = new DataGridViewComboBoxCell();
            cbc.Items.Add("Chua Tra");
            cbc.Items.Add("Da Tra");
            this.dgvQLChiTieu[5, 0] = cbc;
            this.dgvQLChiTieu[5, 0].Value = cbc.Items[0];
            for (int i = 1; i < n; i++)
            {
                cbc = new DataGridViewComboBoxCell();
                cbc.Items.Add("Chua Tra");
                cbc.Items.Add("Da Tra");
                this.dgvQLChiTieu[5, i] = cbc;
                if (this.dgvQLChiTieu[5, i].Value.ToString().Substring(0, 1) == "C")
                {
                    this.dgvQLChiTieu[5, i].Value = cbc.Items[0];
                }
                if (this.dgvQLChiTieu[5, i].Value.ToString().Substring(0, 1) == "D")
                {
                    this.dgvQLChiTieu[5, i].Value = cbc.Items[1];
                }
            }
        }
        #endregion

        #region Delete
        private void bubbleButtonDelete_Click(object sender, DevComponents.DotNetBar.ClickEventArgs e)
        {
            switch(this.tabMain.SelectedIndex)
            {
                case 1:
                    XoaChiTieu(sender, e);
                    break;
                case 3:
                    ThuNhap tn = takeTNRow();
                    MessageBox.Show(im.thuNhapDelete(tn));
                    this.dataGridViewTN.DataSource = null;
                    thuNhapShow();
                    break;
                case 7:
            NhacNhoTuyChon a = takeNNRow();
            MessageBox.Show(pm.nhacNhoDelete(a));
            this.dataGridViewNNTuyChon.DataSource = null;
            nhacNhoShow();
            break;
                case 10:
            KeHoachChiTieu w = takeKHRow();
            MessageBox.Show(kh.keHoachDelete(w));
            this.dataGridViewKH.DataSource = null;
            keHoachShow();
            break;
            
        }
        }
        public void XoaChiTieu(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("Bạn có chắc chắn muốn xóa", "Thông báo", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                try
                {
                    QuanLyChiTieuEntities context = new QuanLyChiTieuEntities();
                    int ma = (int)(dgvQLChiTieu.SelectedCells[0].Value);
                    ChiTieu ct = context.ChiTieux.Single(p => p.MaChiTieu == ma);
                    context.DeleteObject(ct);
                    context.SaveChanges();
                    mtExpense_DoubleClick(sender, e);
                    MessageBox.Show("Xóa thành công");
                }
                catch
                {
                    log.WriteFile("Xóa Chi Tiêu Thất Bại");
                    MessageBox.Show("Xóa thất bại");
                }
            }
        }
        #endregion

        #region Update
        private void bubbleButtonUpdate_Click(object sender, DevComponents.DotNetBar.ClickEventArgs e)
        {
            switch (this.tabMain.SelectedIndex)
            {
                case 1:
                    SuaChiTieu(sender, e);
                    break;
                case 7:
                    NhacNhoTuyChon a = takeNNRow();
                    MessageBox.Show(pm.nhacNhoUpdate(a));
                    this.dataGridViewNNTuyChon.DataSource = null;
                    nhacNhoShow();
                    break;
                case 3:
                    ThuNhap tn = takeTNRow();
                    MessageBox.Show(im.thuNhapUpdate(tn));
                    this.dataGridViewTN.DataSource = null;
                    thuNhapShow();
                    break;
                case 10:
                    KeHoachChiTieu p = takeKHRow();
                    MessageBox.Show(kh.keHoachUpdate(p));
                    this.dataGridViewKH.DataSource = null;
                    keHoachShow();
                    break;
            }
        }
        public void SuaChiTieu(object sender, EventArgs e)
        {
            try
            {
                int giatri = (int)(dgvQLChiTieu.SelectedCells[0].Value);
                QuanLyChiTieuEntities context = new QuanLyChiTieuEntities();
                ChiTieu ct = context.ChiTieux.Single(p => p.MaChiTieu == giatri);
                String ttChiTieu = ct.TrangThai;
                ct.TenChiTieu = (string)(dgvQLChiTieu.SelectedCells[1].Value);
                ct.SoTien = (double)(dgvQLChiTieu.SelectedCells[2].Value);
                ct.ThoiGian = (DateTime)(dgvQLChiTieu.SelectedCells[3].Value);
                ct.MoTa = (string)(dgvQLChiTieu.SelectedCells[4].Value);
                ct.TrangThai = dgvQLChiTieu.SelectedCells[5].Value.ToString();
                context.SaveChanges();
                if ((ct.TrangThai.CompareTo(ttChiTieu)==0)&&ct.TrangThai.Substring(0, 1) == "D")
                {
                    Double money = Double.Parse(this.reMoney.ReadFile());
                    money = money - ct.SoTien;
                    reMoney.WriteFile(money.ToString());
                    reMoney_load();
                }
                mtExpense_DoubleClick(sender, e);
                MessageBox.Show("Sửa thành công");
            }
            catch
            {
                log.WriteFile("Sửa Chi Tiêu Thất Bại");
                MessageBox.Show("Sửa thất bại");
            }
        }
        #endregion

        #region Print
        private void bubbleButtonPrint_Click(object sender, DevComponents.DotNetBar.ClickEventArgs e)
        {
            switch (this.tabMain.SelectedIndex)
            {
                case 3:
                    FrmInAllTN rni = new FrmInAllTN();
                    rni.ShowDialog();
                    break;
                case 1:
                    FormRP rp = new FormRP();
                    rp.ShowDialog();
                    break;
            }
        }
        #endregion

        public string _button1
        {
            get { return dataGridViewTN.SelectedCells[0].Value.ToString(); }
        }
        public string _button2
        {
            get { return dgvQLChiTieu.SelectedCells[0].Value.ToString(); }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void inToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //FrmInTN_Chon inc = new FrmInTN_Chon();

            INTN_TuyChon inc = new INTN_TuyChon();
            inc.Button = _button1;
            inc.ShowDialog();
        }
        #region ThongBao
        void Prompt_ThongBao()
        {
            String[] s = pm.thongbao();
            for (int i = 0; i < s.Length; i++)
                if (s[i] != null)
                    MessageBox.Show(s[i]);
        }
        void Plan_Thongbao()
        {
            List<KeHoachChiTieu> khct=new List<KeHoachChiTieu>();
            String[] s = kh.thongbao(ref khct);
            for (int i = 0; i < s.Length; i++)
                if (s[i] != null)
                {
                    int j = 0;
                    MessageBox.Show(s[i]);
                    
                    ThemChiTieu(khct[j].TenKeHoach, khct[j].SoTien, DateTime.Today, khct[j].MoTa);
                    j++;
                    if (switchButton == 1)
                    {
                        if (MessageBox.Show("bạn có muốn thêm 1 kế hoạch nữa hay không", "nhắc nhở", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            this.tabMain.SelectedIndex = 10;
                            keHoachShow();
                        }
                    }
                }
        }
        #endregion

        private void labelItem12_Click(object sender, EventArgs e)
        {

        }

        private void bubbleButtonKH_Click(object sender, DevComponents.DotNetBar.ClickEventArgs e)
        {
            this.tabMain.SelectedIndex = 10;
            keHoachShow();
            this.kehoachEnable();
        }
        private void bubbleButtonKH_Click(object sender, EventArgs e)
        {
            this.tabMain.SelectedIndex = 10;
            keHoachShow();
            this.kehoachEnable();
        }
        private void bubbleButtonFind_Click(object sender, DevComponents.DotNetBar.ClickEventArgs e)
        {
            switch (this.tabMain.SelectedIndex)
            {
                case 1:
                    {
                            FormTimKiem frmtimkiem = new FormTimKiem();
                            frmtimkiem.ShowDialog();
                            if (!frmtimkiem.Visible && frmtimkiem.result != null)
                            {
                                dgvQLChiTieu.DataSource = frmtimkiem.result;
                                tabMain.SelectedIndex = 1;
                            }
                    }
                    break;
                case 3:
                    FrmTK_TN ftk = new FrmTK_TN();
                        ftk.ShowDialog();
                        if (!ftk.Visible && ftk.result != null)
                        {
                            dataGridViewTN.DataSource = ftk.result;
                            tabMain.SelectedIndex = 3;
                        }
                    break;
            }
        }

        #region Chart
        private void inDòngToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmInTN_Chon inc = new FrmInTN_Chon();
            inc._button = _button1;
            inc.ShowDialog();
        }

        private void inTấtCảToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmInAllTN FrRP = new FrmInAllTN();
            FrRP.Show();
        }

        private void xóaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            XoaChiTieu(sender, e);
        }

        private void thêmToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ThemChiTieu(sender, e);
        }

        private void sửaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SuaChiTieu(sender, e);
        }

        private void inToolStripMenuItem1_Click(object sender, EventArgs e)
        {
           
        }

        private void inDòngToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            FrmInCTTC InTc = new FrmInCTTC();
            InTc.Button = _button2;
            InTc.ShowDialog();
        }

        private void inTấtCảToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            FormRP FrRP = new FormRP();
            FrRP.Show();
        }

        private void thêmToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            ThemChiTieu(sender, e);
        }

        private void sửaToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            SuaChiTieu(sender, e);
        }

        private void bubbleButtonChart_Click(object sender, DevComponents.DotNetBar.ClickEventArgs e)
        {
            DoThi dt = new DoThi();
            dt.ShowDialog();
            this.keHoachShow();
        }

        #endregion

        private void nodeChart_NodeClick(object sender, EventArgs e)
        {
            DoThi dt = new DoThi();
            dt.ShowDialog();
        }

        private void dgvQLChiTieu_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("lỗi kiểu dữ liệu nhập vào");
        }

        #region enable button
        void tn_ctEnable()
        {
            this.bubbleButtonKH.Enabled = false;
            this.bubbleButtonPrint.Enabled = true;
            this.bubbleButtonUpdate.Enabled = true;
            this.bubbleButtonFind.Enabled = true;
            this.bubbleButtonDelete.Enabled = true;
            this.bubbleButtonChart.Enabled = false;
            this.bubbleButtonAdd.Enabled = true;
        }
        void thongke_chartEnable()
        {
            this.bubbleButtonKH.Enabled = true;
            this.bubbleButtonPrint.Enabled = false;
            this.bubbleButtonUpdate.Enabled = false;
            this.bubbleButtonFind.Enabled = false;
            this.bubbleButtonDelete.Enabled = false;
            this.bubbleButtonChart.Enabled = true;
            this.bubbleButtonAdd.Enabled = false;
        }
        void mainMenuEnable()
        {
            this.bubbleButtonKH.Enabled = false;
            this.bubbleButtonPrint.Enabled = false;
            this.bubbleButtonUpdate.Enabled = false;
            this.bubbleButtonFind.Enabled = false;
            this.bubbleButtonDelete.Enabled = false;
            this.bubbleButtonChart.Enabled = false;
            this.bubbleButtonAdd.Enabled = false;
        }
        void nhacnhoEnable()
        {
            this.bubbleButtonKH.Enabled = false;
            this.bubbleButtonPrint.Enabled = false;
            this.bubbleButtonUpdate.Enabled = true;
            this.bubbleButtonFind.Enabled = false;
            this.bubbleButtonDelete.Enabled = true;
            this.bubbleButtonChart.Enabled = false;
            this.bubbleButtonAdd.Enabled = true;
        }
        void kehoachEnable()
        {
            this.bubbleButtonKH.Enabled = true;
            this.bubbleButtonPrint.Enabled = false;
            this.bubbleButtonUpdate.Enabled = true;
            this.bubbleButtonFind.Enabled = false;
            this.bubbleButtonDelete.Enabled = true;
            this.bubbleButtonChart.Enabled = true;
            this.bubbleButtonAdd.Enabled = true;
        }
        #endregion

        #region Slide_Show
        private void SplashScreen()
        {
            Application.Run(new SlideShow());
        }
        #endregion
    }
}

//Prompt class
public static class Prompt
{
    public static string ShowDialog(string text, string caption)
    {
        Form prompt = new Form();
        prompt.Width = 230;
        prompt.Height = 180;
        prompt.FormBorderStyle = FormBorderStyle.FixedDialog;
        prompt.Text = caption;
        prompt.StartPosition = FormStartPosition.CenterScreen;
        Label textLabel = new Label() { Left = 10, Top=20, Text=text };
        TextBox textBox = new TextBox() { Left = 10, Top=50, Width=200 };
        Button confirmation = new Button() { Text = "OK", Left=80, Width=50, Top=100 };
        confirmation.Click += (sender, e) => { prompt.Close(); };
        prompt.Controls.Add(textBox);
        prompt.Controls.Add(confirmation);
        prompt.Controls.Add(textLabel);
        prompt.AcceptButton = confirmation;
        prompt.ShowDialog();
        return textBox.Text;
    }
}